package cn.northsea.controller;

import cn.northsea.pojo.Supplier;
import cn.northsea.service.SupplierService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;

    @RequestMapping("/getList")
    public String getList(@RequestParam(required = false,defaultValue = "1") Integer currPage,
                          @RequestParam(required = false,defaultValue = "10") Integer pageSize,
                          String supName, Model model){
        if(Objects.equals(supName, "")){
            supName = null;
        }
        PageHelper.startPage(currPage,pageSize);
        List<Supplier> supList = supplierService.getList(supName);
        PageInfo<Supplier> pageInfo = new PageInfo<>(supList);
        if(supList != null){
            model.addAttribute("pageInfo",pageInfo);
            model.addAttribute("name",supName);
        }else{
            model.addAttribute("error","当前暂时没有数据，快去添加吧！！！");
            model.addAttribute("name",supName);
        }
        return "erpSupplierList";
    }

    @PostMapping("/insertSupplier")
    private String insertSupplier(Supplier supplier,Model model){
        supplierService.insertSupplier(supplier);
        model.addAttribute("msg","新增成功啦");
        return "titleMsg";
    }

    @RequestMapping("/getSupplier")
    @ResponseBody
    private Supplier getSupper(Integer supplierId){
        return supplierService.getSupplier(supplierId);
    }

    @PostMapping("/updateSupplier")
    private String updateSupplier( Supplier supplier,Model model){
        supplierService.updateSupplier(supplier);
        model.addAttribute("msg","修改成功啦");
        return "titleMsg";
    }

    @RequestMapping("/deleteSupplier")
    private String deleteSupplier(Integer[] ids){
        if(ids != null){
            supplierService.deleteSupplier(ids);
        }
        return "redirect:/supplier/getList.do";
    }
}
